#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "Backend.h"
#include "QQmlContext"

/**本例以backend.h backend.cpp 编写后端接口；main.qml编写前端界面
**/

static QObject *GetBackend(QQmlEngine *engine, QJSEngine *scriptEngine)//定义一个用于qmlRegisterSingletonType接收的实例
{
    Q_UNUSED(engine);
    Q_UNUSED(scriptEngine);

    return Backend::instance();
}
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine; //创建QQmlApplicationEngine实例，用于加载和运行QML文件
    const QUrl url(QStringLiteral("qrc:/main.qml")); //指定QML文件为main.qml
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);//信号槽连接，以确保在QML对象在未成功创建时，退出应用程序

    qmlRegisterSingletonType<Backend>("My.Backend", 1, 0, "Backend", GetBackend);  //方法1，将后端单例注册到QML使用
    engine.rootContext()->setContextProperty("Backend2", new Backend2);//方法2， 将后端实例设置成QML的属性使用
    engine.load(url);//加载.qml文件并显示界面

    return app.exec();
}
